package edu.xpu.project.user.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import edu.xpu.project.user.entity.StudentClass;
import edu.xpu.project.user.repository.StudentClassRepository;

@Service
@Transactional(readOnly=true)
public class StudentClassServiceImpl implements StudentClassService {
	
	@Autowired
	private StudentClassRepository studentClassRepository;

	@Override
	public StudentClass get(Long id) {
		return studentClassRepository.findOne(id);
	}

	@Transactional(readOnly=false)
	@Override
	public StudentClass saveOrUpdate(StudentClass t) {
		//去除重复信息
		String className = t.getClassName();
		StudentClass byClassName = getByClassName(className);
		/*
		 * 如果查询为null, 则插入信息. 否则不插入该信息
		 */
		if (byClassName == null) {
			byClassName = studentClassRepository.saveAndFlush(t);
		}
		return byClassName;
	}

	@Transactional(readOnly=false)
	@Override
	public void delete(Long id) {
		studentClassRepository.delete(id);
	}

	@Override
	public StudentClass getByClassName(String className) {
		return studentClassRepository.findByClassName(className);
	}

	@Override
	public Page<StudentClass> getPageByCriterias(String pageNumberStr, String pageSizeStr, final StudentClass studentClass) {
		Integer pageNumber = 1;
		Integer pageSize = 10;
		try {
			pageNumber = Integer.parseInt(pageNumberStr);
		} catch (Exception e) {}
		try {
			pageSize = Integer.parseInt(pageSizeStr);
		} catch (Exception e) {}
		Pageable pageable = new PageRequest(pageNumber - 1, pageSize, new Sort(Direction.ASC, "className"));
		
		return studentClassRepository.findAll(new Specification<StudentClass>() {
			@Override
			public Predicate toPredicate(Root<StudentClass> root, CriteriaQuery<?> query,
					CriteriaBuilder builder) {
				if (studentClass == null) {
					return null;
				}
				//添加查询条件
				List<Predicate> predicates = new ArrayList<Predicate>(3);
				
				
				if (predicates.size() == 0) {
					return null;
				}
				Predicate[] predArr= new Predicate[predicates.size()];
				return builder.and(predicates.toArray(predArr));
			}
		}, pageable);
	}

}
